# -*- coding:utf-8 -*-
import os


def get_path(image):
    name = image["name"]
    if name == "gline":
        return "/home/bianhui/gmes/app/line/dk/ver"

    return "/home/bianhui/gmes/serve/%s/dk/ver" % name


def run_cmd(cmd):
    os.system("../../cmd/sh/%s" % cmd)


def out_image(image, restart, f):
    fo = open(get_path(image), "r")
    v = fo.readline()
    tmp = v.split()
    ver = tmp[0]

    run_cmd("d.sh %s %s %s" % (f, image["name"], ver))

    if "vol" in image:
        run_cmd("e.sh %s %s" % (f, image["vol"]))

    run_cmd("f.sh %s" % f)

    if "wlinepos" in image:
        run_cmd("p.sh %s" % (f))
    else:
        run_cmd("h.sh %s %s" % (f, image["port"]))

    run_cmd("c.sh %s" % (f))
    run_cmd("kn.sh %s" % f)


def out_proxy(image, restart, f):
    fo = open("./proxy/ver", "r")
    v = fo.readline()
    tmp = v.split()
    ver = tmp[0]

    run_cmd("b.sh %s %s" % (f, ver))

    for d in image["img"]:
        run_cmd("k.sh %s %s" % (f, d["name"]))

    if restart:
        run_cmd("c.sh %s" % (f))

    run_cmd("kn.sh %s" % f)


def out_compose_file(image, path):
    f = path + "docker-compose.yml"

    run_cmd("a.sh %s" % (f))

    restart = image["restart"]

    out_proxy(image, restart, f)

    for d in image["img"]:
        out_image(d, restart, f)

    run_cmd("j.sh %s" % (f))


def out_proxy_file(image, f):
    run_cmd("pa.sh %s" % (f))

    for d in image["img"]:
        run_cmd("pb.sh %s %s %s" % (f, d["name"], d["port"]))

    run_cmd("pc.sh %s" % (f))


def out_img(image, path):
    for d in image["img"]:
        if "dp" in d:
            tmp = d["dp"]
            if tmp == "tar":
                os.system("../../cmd/saveimg.sh %s %s" % (path, d["name"]))
                continue

        os.system("../../cmd/img.sh %s %s" % (path, d["name"]))


def w_out_file(data):
    ver = data["ver"]

    path = "./output/mes_%s/serve/front/" % ver
    os.system("mkdir -p %simg/proxy" % path)

    print("...................................export proxy config")

    run_cmd("proxy.sh %s" % path)

    image = data

    f = "./output/mes_%s/serve/front/img/proxy/default.conf" % ver

    out_proxy_file(image, f)

    img = [{
        "name": "gline",
        "dp": "tar",
        "wlinepos": "1",
        }]

    for d in image["img"]:
        img.append(d)

    image["img"] = img

    print("...................................export docker-compose config")
    out_compose_file(image, path)

    os.system("../../cmd/gen/ngen.sh %s" % path)

    out_img(image, path)
